# ----------------------------------------------------------------------------
#       Copyright (C) 2013-2014 Huynh Vi Lam  <domovilam@gmail.com>
#
#       This file is part of pimucha.
#
#	This program is free software: you can redistribute it and/or modify
#	it under the terms of the GNU General Public License as published by
#	the Free Software Foundation, either version 3 of the License, or
#	(at your option) any later version.
#	
#	This program is distributed in the hope that it will be useful,
#	but WITHOUT ANY WARRANTY; without even the implied warranty of
#	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#	GNU General Public License for more details.
#	
#	You should have received a copy of the GNU General Public License
#	along with this program.  If not, see <http://www.gnu.org/licenses/>.
# ----------------------------------------------------------------------------


import logging
logger = logging.getLogger()

from piHAlibs import (my_fctname,coroutine,db2dict,tstampdev,sensorid)
try:
    from .rfxtrxlibs import *
except ImportError as e:
    logger.critical("%s : %s", repr(e.__class__), str(e))
    print ('RFXtrx modules not yet installed')


@my_fctname
@coroutine
def sensordecoder(targets,rejected=None,newids=None,rawevt=None):
    """
    Decoders for Oregon sensor events from RFXTRX
    """
    condition = " WHERE typeunit = 'sensor'"
    ids = db2dict('UNITIDS',condition)
    rows = RFXTRXDECODERS
    while True:
        msgs = (yield)
       	logger.debug("Msgs received %s",repr(msgs))
        namedev, type, subtype, data, p, protocol, revt, decrow = msgs
        if protocol != 'oregon' : continue
       	logger.debug("Protocol %s type %s subtype %s",protocol, type, subtype)
        if decrow in rows:
            row = rows[decrow]
        else:
            if rejected: rejected.send(['DECODER_NOT_IMPLEMENTED',protocol] + msgs)
            continue
        model = type2model(type,subtype)
       	ld = row[0].split()
       	try:
       	    res = eval(row[1])
       	except Exception as e:
       	    logger.debug("Exception / Error %s",repr(e))
       	    if rejected: rejected.send(['ERR_DECODE',repr(row[1])] + msgs)
       	    continue
       	#Sensor Unit / Id
        unit = model
        if 'AddrId' in ld:
            addr = res[ld.index('AddrId')]
            logger.debug("Address of Sensor  %s",addr)
            unit = model + '_' + addr
            V = (protocol,unit)
       	    if V not in ids:
                logger.debug("New sensor detected %s", repr(V))
                if newids: ids = sensorid([protocol,type + '_' + subtype,'sensor', unit,type,subtype,row[0]])
       	        continue
       	hd = tstampdev(namedev)
       	for d in ld:
       	    event = hd + ['sensor'] + [d, unit, res[ld.index(d)]]
            logger.debug("Function sensordecoder for %s",repr(event))
            for target in targets:
                target.send(event)

